/**
 * @description Axios instance function
 */

import axios from 'axios'
import { notification } from 'vue-antd-ui'
import { messages } from '../i18n/i18nProvider'

const instance = axios.create({
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
})

// Intercept request
instance.interceptors.request.use(
  config => {
    // The login interface does not require token information
    if (config.url !== '/login') {
      let token = localStorage.getItem('authenticationToken')
      if (token) config.headers.common['X-Subject-Token'] = token
      else if (process.env.NODE_ENV === 'development') {
        // localStorage.clear()
        // sessionStorage.clear()
      } else {
        window.parent.postMessage({ status: 403 }, '*')
      }
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// Intercept response
instance.interceptors.response.use(
  response => {
    if (
      response.headers &&
      response.headers['x-subject-token'] &&
      response.headers['x-subject-token'] !== 'None'
    )
      localStorage.setItem(
        'authenticationToken',
        response.headers['x-subject-token']
      )

    if (response.config.url === '/users/login')
      return response.headers['x-subject-token'] !== 'None'
        ? response.headers['x-subject-token']
        : null

    return response.data
  },
  err => {
    if (err.response.status === 403) {
      if (process.env.NODE_ENV === 'development') {
        localStorage.clear()
        sessionStorage.clear()
      }

      return Promise.reject(err)
    } else if (err.response.status === 401) {
      notification.warning({
        message: messages.i18n_common_401_title + messages.i18n_common_colon,
        description: messages.i18n_common_401_description
      })
      return Promise.reject(err)
    }

    let msg = messages.i18n_common_service_exception
    if (err.response && err.response.data && err.response.data.message_zh_CN)
      msg = err.response.data.message_zh_CN

    notification.error({
      message: messages.i18n_common_error,
      description: msg
    })
    return Promise.reject(err)
  }
)

export default instance
